//=========================================================================
// Copyright (C) 2025 The C++ Component Model(COMO) Open Source Project
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//      http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//=========================================================================

#include <stdatomic.h>
#include "lamport_clock.h"

void InitLamportClock(LamportClock *clock)
{
    clock->time_ = 0;
}

/**
 * Get current Lamport timestamp.
 *
 * @return Long value.
 */
uint64_t get_time(LamportClock *clock)
{
    return atomic_load(&(clock->time_));
}

/**
 * Handle local event.
 * Increment timer and return the new value.
 *
 * @return uint64_t value;
 */
uint64_t local_event(LamportClock *clock)
{
    return atomic_fetch_add(&(clock->time_), 1);
}

/**
 * Handle send event.
 * Increment local time and return the new value.
 *
 * @return uint64_t value;
 */
uint64_t send_event(LamportClock *clock)
{
    return atomic_fetch_add(&(clock->time_), 1);
}

/**
 * Handle receive event.
 * Receive sender's time and set the local time to the maximum between
 * received and local time plus 1.
 *
 * @param received_time Sender's time.
 * @return uint64_t value;
 */
uint64_t receive_event(LamportClock *clock, uint64_t received_time)
{
    while (1) {
        uint64_t cur = get_time(clock);

        // If received time is old, do nothing.
        if (received_time < cur) {
            return cur;
        }

        // Ensure that local timer is at least one ahead.
        if (! atomic_compare_exchange_strong(&(clock->time_), &cur, received_time + 1)) {
            continue;
        }
        else {
            break;
        }
    }

    return received_time + 1;
}
